package com.zjlanyun.erp.interior.warehouse;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.aihook.alertview.library.AlertView;
import com.aihook.alertview.library.OnItemClickListener;
import com.alibaba.fastjson.JSON;
import com.yolanda.nohttp.rest.Response;
import com.zjlanyun.erp.Data;
import com.zjlanyun.erp.MainApplication;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.config.AppConfig;
import com.zjlanyun.erp.interior.CommonList;
import com.zjlanyun.erp.interior.production.Loading;
import com.zjlanyun.erp.network.WebApi;
import com.zjlanyun.erp.nohttp.HttpRequest;
import com.zjlanyun.erp.nohttp.SimpleHttpListener;
import com.zjlanyun.erp.rfid.m10.u8.activity.OutPowerActivity;
import com.zjlanyun.erp.utils.Toastor;
import com.zjlanyun.erp.view.BaseRFIDActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

public class Inventory extends BaseRFIDActivity {

    @Bind(R.id.lv) ListView lv;
    @Bind(R.id.btn_merge) Button btn_merge;
    @Bind(R.id.tv_result) TextView tv_result;
    @Bind(R.id.tv_content) TextView tv_content;


    private boolean scaning = false; //是否正在扫描
    private boolean isPause = false; //是否暂停
    private EPCAdapter epcAdapter;
    private InventoryAdapter inventoryAdapter;
    private List<InventoryModel.ListBean> inventoryData;
    private boolean isMerge = false;
    private ArrayList<String> allInvData;
    private ArrayList<String> invData;
    private String apiUrl;
    private int FInterID = 0;
    private ArrayList<HashMap<String, Object>> mStockList;

    public static final int REQUESTCODE_SELECTSTOCK = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inventory);
        ((MainApplication) getApplication()).addActivity(this);
        initBaseView();
        initView();
    }

    /**
     * 初始化View
     */
    private void initView() {
        Bundle bundle = getIntent().getExtras();
        title.setText(bundle.getString("title"));
        btn_merge.setVisibility(View.VISIBLE);
        apiUrl = WebApi.warehouse();

        allInvData = new ArrayList<>();
        invData = new ArrayList<>();
        epcAdapter = new EPCAdapter(mContext, data);
        inventoryData = new ArrayList<>();
        inventoryAdapter = new InventoryAdapter(mContext, inventoryData);
        getInventoryInterID();

        ll_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (invData.size() > 0) {
                    new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            if (position == 0) {
                                finish();
                            }
                        }
                    }).show();
                } else {
                    finish();
                }
            }
        });
    }

    /**
     * 合并
     */
    @OnClick(R.id.btn_merge)
    public void merge() {
        if (isMerge) {
            isMerge = false;
            btn_merge.setText("合并");
        } else {
            isMerge = true;
            btn_merge.setText("分开");
        }
        query();
    }

    /**
     * 开始扫描
     */
    public void startScan() {
        isMerge = false;
        btn_merge.setText("合并");
        scaning = true;
        lv.setAdapter(epcAdapter);
        super.startScan();
    }

    /**
     * 暂停扫描
     */
    private void pauseScan() {
        if (isPause) {
            isPause = false;
            m_curInventoryBuffer.bLoopCustomizedSession = true;
            m_curInventoryBuffer.btSession = (byte) (getSessionState() & 0xFF);
            m_curInventoryBuffer.btTarget = (byte) (getFlagState() & 0xFF);
            m_curInventoryBuffer.lAntenna.add((byte) 0x01);
            m_curInventoryBuffer.bLoopInventoryReal = true;
            m_curInventoryBuffer.btRepeat = (byte) 1;
            mReaderHelper.setInventoryFlag(true);
            byte btWorkAntenna = m_curInventoryBuffer.lAntenna.get(m_curInventoryBuffer.nIndexAntenna);
            if (btWorkAntenna < 0)
                btWorkAntenna = 0;
            mReader.setWorkAntenna(m_curReaderSetting.btReadId, btWorkAntenna);
            // Loger.disk_log("调试", "开始盘询，天线设置完毕", "M10_U8");
            m_curReaderSetting.btWorkAntenna = btWorkAntenna;
            mHandler.removeCallbacks(mRefreshRunnable);
            mHandler.postDelayed(mRefreshRunnable, 500);
        } else {
            tv_result.setText(String.format("暂停中：%d个", m_curInventoryBuffer.lsTagList.size()));
            isPause = true;
            mReaderHelper.setInventoryFlag(false);
            m_curInventoryBuffer.bLoopInventory = false;
            m_curInventoryBuffer.bLoopInventoryReal = false;
            mLoopHandler.removeCallbacks(mLoopRunnable);
            mHandler.removeCallbacks(mRefreshRunnable);
        }
    }

    /**
     * 停止扫描
     */
    public void stopScan() {
        if (scaning) {
            isPause = false;
            scaning = false;
            super.stopScan();
            tv_result.setText(String.format("盘询结束：%d个", m_curInventoryBuffer.lsTagList.size()));
            String epc = "";
            for (int i = 0; i < m_curInventoryBuffer.lsTagList.size(); i++) {
                epc = m_curInventoryBuffer.lsTagList.get(i).getStrEPC().replace(" ", "");
                if (!allInvData.contains(epc)) {
                    invData.add(epc);
                    allInvData.add(epc);
                }
            }
            tv_content.setText(String.format("盘点：%d/%d", allInvData.size() - invData.size(), allInvData.size()));
        }
    }

    public void refreshList() {
        super.refreshList();
        epcAdapter.notifyDataSetChanged();
    }

    public void refreshText() {
        tv_result.setText(String.format("盘询中：%d个", m_curInventoryBuffer.lsTagList.size()));
    }

    /**
     * 查询
     */
    @OnClick(R.id.btn_query)
    public void query() {
        stopScan();
        inventoryData.clear();
        lv.setAdapter(inventoryAdapter);
        if (AppConfig.getInstance().getBoolean("isDemo", true)) {

        } else {
            StringBuffer epcs = new StringBuffer();
            for (String str : invData) {
                if (epcs.length() > 0)
                    epcs.append(",");
                epcs.append("'" + str + "'");
            }
            HashMap<String, Object> param = new HashMap<>();
            param.put("epcs", epcs.toString());
            param.put("merge", isMerge);
            param.put("FActionFlag", "query");
            HttpRequest client = new HttpRequest(mContext, apiUrl, "postInventory", JSON.toJSONString(param), true, true);
            client.send(new SimpleHttpListener<JSONObject>() {
                @Override
                public void onSucceed(int what, Response<JSONObject> response) {
                    InventoryModel data = JSON.parseObject(response.get().optString("data").toString(), InventoryModel.class);
                    for (int i = 0; i < data.getList().size(); i++) {
                        InventoryModel.ListBean model = new InventoryModel.ListBean();
                        model.setFNumber(data.getList().get(i).getFNumber());
                        model.setFName(data.getList().get(i).getFName());
                        model.setFQty(data.getList().get(i).getFQty());
                        model.setFCLQty(data.getList().get(i).getFCLQty());
                        model.setFGongxuName(data.getList().get(i).getFGongxuName());
                        model.setFPosition(data.getList().get(i).getFPosition());
                        inventoryData.add(model);
                    }
                    inventoryAdapter.notifyDataSetChanged();
                }
            });
        }
    }

    /**
     * 提交
     */
    @OnClick(R.id.btn_submit)
    public void submit() {
        stopScan();
        if (FInterID == 0) {
            Toastor.getInstance().showShortToast("单据ID获取失败");
            return;
        } else if (invData.size() == 0) {
            Toastor.getInstance().showShortToast("无数据提交");
            return;
        }

        if (mStockList != null) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "选择仓库");
            bundle.putIntArray("layout", new int[]{R.id.tv1});
            bundle.putStringArray("field", new String[]{"FName"});
            bundle.putString("list", JSON.toJSONString(mStockList));
            bundle.putString("action", "common");
            Intent intent = new Intent(mContext, CommonList.class);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUESTCODE_SELECTSTOCK);
        }
    }

    /**
     * 获取盘点的FInterID
     */
    private void getInventoryInterID() {
        HttpRequest client = new HttpRequest(mContext, apiUrl, "getInventoryInterID", true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                JSONObject data = response.get().optJSONObject("data");
                FInterID = data.optInt("FInterID");

                mStockList = new ArrayList<>();
                JSONArray stock = data.optJSONArray("stock");
                for (int i = 0; i < stock.length(); i++){
                    JSONObject item = stock.optJSONObject(i);
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("FName", item.optString("FName"));
                    map.put("FNumber", item.optString("FNumber"));
                    mStockList.add(map);
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 80 && Build.MODEL.equals(Data.RFID_DEVICE)) {
            if (scaning) {
                pauseScan();
            } else {
                startScan();
            }
        } else if (keyCode == 1 && Build.MODEL.equals(Data.RFID_DEVICE)) {
            query();
        } else if (keyCode == 2 && Build.MODEL.equals(Data.RFID_DEVICE)) {
            submit();
        } else if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (invData.size() > 0) {
                new AlertView("提示", "有未提交的数据，确定退出当前页吗？", "取消", new String[]{"确定"}, null, mContext, AlertView.Style.AlertDialog, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            finish();
                        }
                    }
                }).show();
                return false;
            }
        } else if ((keyCode == 131 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 132 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 133 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            Intent intent = new Intent(mContext, OutPowerActivity.class);
            intent.putExtra("from", "RFID" + className);
            startActivity(intent);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE_SELECTSTOCK && resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            int p = bundle.getInt("position");
            HashMap<String, Object> param = new HashMap<>();
            param.put("epcs", JSON.toJSONString(invData));
            param.put("FActionFlag", "submit");
            param.put("FInterID", FInterID);
            param.put("FNumber", mStockList.get(p).get("FNumber").toString());
            HttpRequest client = new HttpRequest(mContext, apiUrl, "postInventory", JSON.toJSONString(param), true, true);
            client.send(new SimpleHttpListener<JSONObject>() {
                @Override
                public void onSucceed(int what, Response<JSONObject> response) {
                    Toastor.getInstance().showShortToast(R.string.submit_success);
                    invData.clear();
                    inventoryData.clear();
                    cleanData();
                    epcAdapter.notifyDataSetChanged();
                    inventoryAdapter.notifyDataSetChanged();
                    tv_content.setText(String.format("盘点：%d/%d", allInvData.size() - invData.size(), allInvData.size()));
                }
            });
        }
    }

    private void cleanData(){
        data.clear();
    }
}
